package com.guchenbo.example.proxy;

import net.sf.cglib.proxy.*;

import java.lang.reflect.Method;

public class CglibDemo {
    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setClassLoader(SmsService.class.getClassLoader());
        enhancer.setSuperclass(SmsService.class);

        Callback[] callbacks = new Callback[2];
        callbacks[0] = new DemoMethodInterceptor();
        callbacks[1] = new DemoMethodInterceptor2();
        enhancer.setCallbacks(callbacks);
        enhancer.setCallbackFilter(new CallbackFilter() {
            @Override
            public int accept(Method method) {
                if (method.getName().equals("hashCode")) {
                    return 0;
                }
                return 1;
            }
        });

        SmsService service = (SmsService) enhancer.create();
        service.send("jay");
        service.hashCode();
        service.equals(new Object());

    }

    public static class DemoMethodInterceptor implements MethodInterceptor {
        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("DemoMethodInterceptor");
            return methodProxy.invokeSuper(o, objects);
        }
    }

    public static class DemoMethodInterceptor2 implements MethodInterceptor {
        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("DemoMethodInterceptor2");
            return methodProxy.invokeSuper(o, objects);
        }
    }
}
